package com.joint.base.service.redis;

import com.fz.us.base.util.LogUtil;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * Created by hpj on 2015/4/10.
 */
public class JediesClient implements DisposableBean {
    private RedisTemplate redisTemplate;

    /**
     * set方法
     * @param key
     * @param value
     */
    public void set(final String key,final String value){
        redisTemplate.execute(new RedisCallback() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                connection.set(
                        redisTemplate.getStringSerializer().serialize(key),
                        redisTemplate.getStringSerializer().serialize(value)
                );
                return null;
            }
        });

    }

    /**
     * get方法
     * @param key
     * @return
     */
    public String get(final String key){

        Object obj = redisTemplate.execute(new RedisCallback() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                byte[] keyBytes = redisTemplate.getStringSerializer().serialize(key);
                if (connection.exists(keyBytes)) {
                    byte[] value = connection.get(keyBytes);
                    String jInfo = (String) redisTemplate.getStringSerializer().deserialize(value);
                    return jInfo;
                }
                return null;
            }
        });
        LogUtil.info("{ Object }"+obj);
        return (String) obj;
    }

    /**
     * 删除
     * @param key
     */
    public void delete(final String key){
        redisTemplate.execute(new RedisCallback() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                byte[] keyBytes = redisTemplate.getStringSerializer().serialize(key);
                connection.del(keyBytes);
                return null;
            }
        });
    }

    @Override
    public void destroy() throws Exception {}

    public RedisTemplate getRedisTemplate() {
        return redisTemplate;
    }

    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
}
